<script lang="ts">
export default {
  name: "BodyMoving"
}
</script>

<script lang="ts" setup>
import {computed, onMounted, onUnmounted, ref} from "vue"
import useDep from "./use-dep"

type Props = {
  json?: string;
  config?: any;
  width?: string;
  height?: string;
};

const defaultConfig = {
  loop: true,
  autoplay: true
}

const win: any = window

const props = defineProps<Props>()

const movingTargetRef = ref<any>()

let animation: any

function startAnimate() {
  animation = win.bodymovin.loadAnimation({
    container: movingTargetRef.value,
    path: props.json,
    ...defaultConfig,
    ...props.config
  })
}

function getAnimation() {
  return animation
}

const useStyle = computed(() => {
  return {
    width: props.width || "100rem",
    height: props.height || "100rem"
  }
})

const start = (function () {
  let count = 0
  return function () {
    if (win.bodymovin) {
      startAnimate()
      count = 0
    } else {
      if (count <= 5) {
        count += 1
        setTimeout(() => {
          start()
        }, 60)
      }
    }
  }
})()

onMounted(async () => {
  await useDep()
  start()
})

onUnmounted(() => {
  animation && animation.destroy()
})

defineExpose({
  getAnimation
})
</script>

<template>
  <div ref="movingTargetRef" :style="useStyle" class="moving-target"></div>
</template>
